package com.clkj.xiuzheng.service.shangcheng;

import com.clkj.xiuzheng.dao.shangcheng.*;
import com.clkj.xiuzheng.pojo.Product;
import com.clkj.xiuzheng.pojo.shangcheng.SProduct;
import com.clkj.xiuzheng.pojo.common.OSSUtil;
import com.clkj.xiuzheng.pojo.shangcheng.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;

@Service
public class ScProductServiceImpl implements ScProductService{

    @Autowired
    private ScProductMapper scProductMapper;
    @Autowired
    private ScProductCategoryMapper scProductcategoryMapper;
    @Autowired
    private ScProductcommentMapper scProductcommentMapper;
    @Autowired
    private ScProductformatMapper scProductformatMapper;
    @Autowired
    private ScProductimageMapper  scProductimageMapper;
    @Autowired
    private ScUserMapper scUserMapper;
    @Autowired
    private ScOrderMapper scOrderMapper;
    @Autowired
    private ScOrderInfoMapper scOrderInfoMapper;

    @Autowired
    private CollectOrPriseMapper collectOrPriseMapper;

    @Autowired
    private ScDiscussionMapper discussionMapper;

    private Map map;

    @Override
    public PageInfo getProductByCategoryId(Integer categoryId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        Example example =  new Example(SProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryThreeId",categoryId);
        criteria.andEqualTo("productStatus",1);
        criteria.andEqualTo("productType",0);
        List<SProduct> list = scProductMapper.selectByExample(example);
        return new PageInfo(list);
    }



    @Override
    public SProduct getProductById(Integer productId) {
        //查询商品详情
        SProduct product = scProductMapper.getProductById(productId);
        //查询评论总数
//        Integer commentNum = scProductcommentMapper.CountCommentById(product.getProductId());
//        product.setScProductcommentNum(commentNum);
//        //查询前三个评论
//        List<ProductComment> list = scProductcommentMapper.selectTop3CommentByProductId(productId);
//        product.setScProductcommentList(list);
       //查询商品分类名称
//        SProduct scProduct1 = scProductMapper.selectCategoryNameById(productId);
//        SProduct.setCategoryOneName(scProduct1.getCategoryOneName());
//        SProduct.setCategoryTwoName(scProduct1.getCategoryTwoName());
//        SProduct.setCategoryThreeName(scProduct1.getCategoryThreeName());
//        SProduct.setFactoryName(scProduct1.getFactoryName());
        //根据商品id查询商品下的规格信息
        Example example1 =  new Example(ProductFormat.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("productId",productId);
        criteria1.andEqualTo("isDeleted",1);
        List<ProductFormat> productFormats = scProductformatMapper.selectByExample(example1);
        product.setProductFormat(productFormats);
        //根据商品id查询商品轮播图
        Example example2 =  new Example(ProductImage.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("productId",productId);
        criteria2.andEqualTo("imageType",0);
        product.setLunboImage(scProductimageMapper.selectByExample(example2));
        //根据商品id查询商品详情图
        Example example3 =  new Example(ProductImage.class);
        Example.Criteria criteria3 = example3.createCriteria();
        criteria3.andEqualTo("productId",productId);
        criteria3.andEqualTo("imageType",1);
        product.setDetailImage(scProductimageMapper.selectByExample(example3));
        return product;
    }
    @Override
    public PageInfo getProductListByCompanyId(Integer companyId, Integer pageSize, Integer pageNum,String productName, Integer productStatus, Integer productType, Integer categoryOneId,Integer categoryTwoId,Integer categorythreeId) {
        //根据公司id查询所有产品
        PageHelper.startPage(pageNum,pageSize);
        List<SProduct> list = scProductMapper.getProductListByCompanyId(companyId,productName,productStatus,productType,categoryOneId,categoryTwoId,categorythreeId);
        return new PageInfo(list);
    }

    @Override
    public void offProduct(String productIdList, Integer type) {

        Example example =  new Example(SProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("productId", Arrays.asList(productIdList.split(",")));
        SProduct product = new SProduct();
        if (type == 0){
            product.setProductStatus(0);
        }
        if (type == 1){
            product.setProductStatus(1);
        }
        scProductMapper.updateByExampleSelective(product,example);
    }

    @Override
    public Map<String, Object> getHomeInfo(Integer companyId) {
        //获取用户总数
        Example example =  new Example(SUser.class);
        Example.Criteria criteria = example.createCriteria();
        SUser user = new SUser();
        user.setCompanyId(companyId);
        int userNUM = scUserMapper.selectCount(user);
        //获取订单总额
        Double orderTotal = scOrderMapper.selectOrderTotal(companyId);
        //获取总订单数
        Order order = new Order();
        order.setCompanyId(companyId);
        int orderNum = scOrderMapper.selectCount(order);
        //获取今日订单总额
        // 获取今日的开始日期
        LocalDate today = LocalDate.now();
        String nowDays = today.atStartOfDay().toLocalDate().toString();
        // 获取今日的结束日期
        String afterDays = today.plusDays(1).atStartOfDay().toLocalDate().toString();
        //获取今日订单总额
        Double todayOrderTotal = scOrderMapper.selectTodayOrderTotal(companyId,nowDays,afterDays);
        //获取今日订单数
        Integer todayOrderNum = scOrderMapper.selectTodayOrderNum(companyId,nowDays,afterDays);
        Map<String, Object> map = new HashMap<>();
        map.put("userNum",userNUM);
        map.put("orderTotal",orderTotal);
        map.put("orderNum",orderNum);
        map.put("todayOrderTotal",todayOrderTotal);
        map.put("todayOrderNum",todayOrderNum);
        return map;
    }

    @Override
    public List<OrderInfo> getProductCountInfo(Integer productId) {
        Example example =  new Example(OrderInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId);
        List<OrderInfo> list = scOrderInfoMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<SProduct> getProductListByCompanyIdNoPage(Integer companyId) {
        Example example =  new Example(SProduct.class);
        example.createCriteria().andEqualTo("companyId",companyId);
        List<SProduct> list = scProductMapper.selectByExample(example);
        return list;
    }

    @Override
    @Transactional
    public void updateProduct(SProduct product, HttpServletRequest request) {
        MultipartFile lunboImage = ((MultipartRequest) request).getFile("headImage");
        MultipartFile video = ((MultipartRequest) request).getFile("video");
        //修改规格图片
        if (product.getProductUpdateFormat() != null) {
            if (!product.getProductUpdateFormat().isEmpty()) {
                //修改规格图片
                    List<ProductFormat> formats = product.getProductUpdateFormat();
                    if (!formats.isEmpty()) {
                        for (int i = 0; i < formats.size(); i++) {
                            int flag = formats.get(i).getFlag();
                            if (flag != -1) {
                                MultipartFile updateFormat = ((MultipartRequest) request).getFile("updateFormatImage" + flag);
                                String formatImage = OSSUtil.uploadingImg(updateFormat, "xiuzheng/scproduct");
                                formats.get(i).setProductImage(formatImage);
                            }
                            scProductformatMapper.updateByPrimaryKeySelective(product.getProductUpdateFormat().get(i));
                            if (formats.get(i).getFormatId() == null) {
                                formats.get(i).setProductId(product.getProductId());
                                scProductformatMapper.insertSelective(formats.get(i));
                            } else {
                                scProductformatMapper.updateByPrimaryKeySelective(formats.get(i));
                            }
                        }
                    }

            }
        }
                    //商品主图
                    if (lunboImage != null) {
                        String image = OSSUtil.uploadingImg(lunboImage, "xiuzheng/scproduct");
                        product.setProductImage(image);
                    }
                    if (video != null) {
                        String image = OSSUtil.uploadingImg(video, "xiuzheng/scproduct");
                        product.setProductVideo(image);
                    }
                    scProductMapper.updateByPrimaryKeySelective(product);
                }




    @Override
    public void getProductByFormatId(ProductFormat productformat, HttpServletRequest request) {
        //规格图片
        MultipartFile lunboImage = ((MultipartRequest) request).getFile("formatImage");
        if (lunboImage != null){
            String image = OSSUtil.uploadingImg(lunboImage, "xiuzheng/scproduct");
            productformat.setProductImage(image);
        }
        scProductformatMapper.updateByPrimaryKeySelective(productformat);
    }

    @Override
    public void deleteImage(Integer imageId) {
        scProductimageMapper.deleteByPrimaryKey(imageId);
    }

    @Override
    public void addImage(Integer productId, HttpServletRequest request) {
        //商品轮播图
        List<MultipartFile> lunboImage = ((MultipartRequest) request).getFiles("lunboImage");
        //商品详情图
        List<MultipartFile> detailImage = ((MultipartRequest) request).getFiles("detailImage");
        //上传商品轮播图
        List<ProductImage> list = new ArrayList<>();
        ProductImage productImage =null;
        if (lunboImage != null){
            for (MultipartFile file : lunboImage) {
                String uploadImage = OSSUtil.uploadingImg(file, "xiuzheng/scproduct");
                productImage =  new ProductImage();
                productImage.setImage(uploadImage);
                productImage.setProductId(productId);
                productImage.setImageType(0);
                productImage.setIsDeleted(0);
                list.add(productImage);
            }
        }
        //上传商品详情图
        if (detailImage != null){
            for (MultipartFile file : detailImage) {
                String uploadImage = OSSUtil.uploadingImg(file, "xiuzheng/scproduct");
                productImage = new ProductImage();
                productImage.setImage(uploadImage);
                productImage.setProductId(productId);
                productImage.setImageType(1);
                list.add(productImage);
            }
        }

        scProductimageMapper.insertList(list);
    }

    @Override
    public Map getDetail(Integer productId,Integer userId) {
        Example example  = new Example(SProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId);
        SProduct product = scProductMapper.selectOneByExample(example);

        example = new Example(ProductImage.class);
        criteria =example.createCriteria();
        criteria.andEqualTo("productId",productId).andEqualTo("isDeleted",1);
        List<ProductImage> imgList = scProductimageMapper.selectByExample(example);

        example = new Example(ProductFormat.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId).andEqualTo("isDeleted",1);
        List<ProductFormat> formatList = scProductformatMapper.selectByExample(example);

        List<ProductComment> commentList = scProductcommentMapper.listTopCommentByProductId(productId);//

        List<ProductDiscussion> discussions = discussionMapper.listTopDiscussionByProductId(productId);

        //是否收藏
        example = new Example(CollectOrPrise.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("productId",productId).andEqualTo("collectType",0).andEqualTo("userId",userId);
        CollectOrPrise collectOrPrise = collectOrPriseMapper.selectOneByExample(example);

        //相关推荐
        example = new Example(SProduct.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("productStatus",1).andEqualTo("productKind",0);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.orEqualTo("categoryTwoId",product.getCategoryTwoId()).orEqualTo("productBrandId",product.getProductBrandId());
        example.and(criteria1);
        List<SProduct> productList = scProductMapper.selectByExample(example);


        map = new HashMap<>();
        map.put("product", product);
        map.put("imgList", imgList);
        map.put("formatList", formatList);
        map.put("commentList", commentList);
        map.put("collectOrPrise", collectOrPrise);
        map.put("productList", productList);
        map.put("discussions", discussions);
        return map;
    }

    @Override
    public List<ProductDiscussion> listDiscussion(Integer productId) {
        return discussionMapper.listDiscussion(productId);
    }

    @Override
    public List<SProduct> searchProduct(String searchName) {
        //相关推荐
        Example example = new Example(SProduct.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andEqualTo("productStatus",1).andEqualTo("productKind",0);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.orLike("productName","%"+searchName+"%").orLike("productDescription","%"+searchName+"%");
        example.and(criteria1);
        List<SProduct> productList = scProductMapper.selectByExample(example);
        return productList;
    }

    @Override
    @Transactional
    public void addProduct(SProduct product, HttpServletRequest request) {
        //商品主图
        MultipartFile headImage = ((MultipartRequest) request).getFile("headImage");
        //商品轮播图
        List<MultipartFile> lunboImage = ((MultipartRequest) request).getFiles("file");
        //商品详情图
        List<MultipartFile> detailImage = ((MultipartRequest) request).getFiles("files");
        //商品视频
        MultipartFile video = ((MultipartRequest) request).getFile("video");
        //规格图片
        List<MultipartFile> formatImage = ((MultipartRequest) request).getFiles("formatImage");
           /* MultipartFile headImage= null;
            List<MultipartFile> lunboImage=null;
            List<MultipartFile> detailImage=null;
            MultipartFile video=null;
            MultipartFile formatImage=null;*/
        //上传商品视频
        if (video != null){
            String uploadVideo = OSSUtil.uploadingImg(video, "xiuzheng/scproduct");
            product.setProductVideo(uploadVideo);
        }
        //上传商品主图
        if (headImage != null){
            String uploadHeadImage  = OSSUtil.uploadingImg(headImage, "xiuzheng/scproduct");
            product.setProductImage(uploadHeadImage);
        }
        //上传商品 获取商品id
        scProductMapper.insertProduct(product);

        //上传商品轮播图
        List<ProductImage> list = new ArrayList<>();
        ProductImage productImage =null;
        if (lunboImage != null){
            for (MultipartFile file : lunboImage) {
                String uploadImage = OSSUtil.uploadingImg(file, "xiuzheng/scproduct");
                productImage =  new ProductImage();
                productImage.setImage(uploadImage);
                productImage.setProductId(product.getProductId());
                productImage.setImageType(0);
                productImage.setIsDeleted(1);
                list.add(productImage);
            }
        }
        //上传商品详情图
        if (detailImage != null){
                for (MultipartFile file : detailImage) {
                    String uploadImage = OSSUtil.uploadingImg(file, "xiuzheng/scproduct");
                    productImage = new ProductImage();
                    productImage.setImage(uploadImage);
                    productImage.setProductId(product.getProductId());
                    productImage.setImageType(1);
                    productImage.setIsDeleted(1);
                    list.add(productImage);
                }
        }

        scProductimageMapper.insertList(list);


        //上传规格和规格图片
        if (formatImage.size()>0){
            List<ProductFormat> list1 = new ArrayList<>();
            for (int i=0;i<formatImage.size();i++){
                String uploadImage = OSSUtil.uploadingImg(formatImage.get(i), "xiuzheng/scproduct");
                product.getProductFormat().get(i).setProductId(product.getProductId());
                product.getProductFormat().get(i).setProductImage(uploadImage);
                product.getProductFormat().get(i).setIsDeleted(1);
                list1.add(product.getProductFormat().get(i));
            }
            scProductformatMapper.insertList(list1);
        }

    }


}
